package com.dzm.phone.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baidubce.http.ApiExplorerClient;
import com.baidubce.http.AppSigner;
import com.baidubce.http.HttpMethodName;
import com.baidubce.model.ApiExplorerRequest;
import com.baidubce.model.ApiExplorerResponse;
import com.dzm.phone.Entity.PhoneInfo;
import com.dzm.phone.service.PhoneService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * @author Dzm
 * @create 2024-04-11-14:23
 */

@Service
public class PhoneServiceImpl implements PhoneService {

    @Override
    @Cacheable(value = "phoneInfo", key = "#phoneNumber")
    public PhoneInfo getPhoneInfo(String phoneNumber) {

        boolean isAdd = false;
        if(phoneNumber.length() == 3) {
            phoneNumber = phoneNumber + "00000000";
            isAdd = true;
        }

        String path = "https://hcapi02.api.bdymkt.com/mobile";
        ApiExplorerRequest request = new ApiExplorerRequest(HttpMethodName.GET, path);
        request.setCredentials("f11a48d700cf46cb88ba1252b3eff7e5", "9d713b829e2140168f1c3c12893b711c");
        request.addHeaderParameter("Content-Type", "application/json;charset=UTF-8");
        request.addQueryParameter("mobile", phoneNumber);

        ApiExplorerClient client = new ApiExplorerClient(new AppSigner());

        ApiExplorerResponse response = client.sendRequest(request);
        //获取所有信息
        JSONObject jsonObject = JSONObject.parseObject(response.getResult());
        String code = jsonObject.getString("code");

        if(code.equals("200")) {
            //获取用户信息
            String data = jsonObject.getString("data");
            JSONObject info = JSONObject.parseObject(data);
            String operator = info.getString("types");
            String location = info.getString("prov") + info.getString("city");

            PhoneInfo phoneInfo = new PhoneInfo();
            phoneInfo.setPhoneNumber(phoneNumber);
            phoneInfo.setOperator(operator);
            phoneInfo.setLocation(location);

            if(isAdd) {
                phoneInfo.setLocation(null);
            }

            return phoneInfo;
        } else {
            //获取错误信息
            String message = jsonObject.getString("message");
            throw new RuntimeException(message);
        }

    }
}
